package com.example.javaee.Interceptor;

import com.example.javaee.Util.JwtTokenUtil;
import com.example.javaee.dao.UserMapper;
import com.example.javaee.domain.User;
import com.example.javaee.exception.LoginException;
import com.sun.istack.internal.NotNull;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//登录检查拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    UserMapper userMapper;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler) throws LoginException {

        if("OPTIONS".equals(request.getMethod().toUpperCase())){
            return true;
        }
        final String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (Strings.isEmpty(header)) {
            throw new LoginException("请先登录");
        }

        Claims claimFromToken = jwtTokenUtil.getClaimFromToken(header);
        String subject = claimFromToken.getSubject();
        User user = userMapper.selectByName(subject);

        if (user == null) {
            throw new LoginException("请重新登录");
        }
        return true;
    }
}